package com.opticon.vaadinR.core.r;

import com.google.common.io.Files;
import com.opticon.vaadinR.core.RFilter;
import com.opticon.vaadinR.core.constants.RConstants;
import com.opticon.vaadinR.exceptions.RVaadinException;
import com.opticon.vaadinR.interfaces.DashBoardManager;
import com.opticon.vaadinR.interfaces.RResultHandler;
import com.vaadin.Application;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.nio.charset.Charset;

/**
 * This class is a
 */
public abstract class AbstractRResultHandler implements RResultHandler {
    private static Logger logger = Logger.getLogger(AbstractRResultHandler.class);

    protected DashBoardManager iDashboard = null;
    protected Application iApplication;

    public AbstractRResultHandler(Application aApplication) {

        iApplication = aApplication;
    }


    public void loadRResults(RFilter aRFilter) {
        try {
            String lTaskSessionWorkSpace =
                    aRFilter.get(RConstants.WORKSPACE) + File.separator +
                            aRFilter.get(RConstants.SESSIONID) + File.separator +
                            aRFilter.get(RConstants.TASKID);

            File lFolder = new File(lTaskSessionWorkSpace);
            if (!lFolder.exists()) {
                String lMessage = String.format("Could not find task|session|workspace folder %s ", lTaskSessionWorkSpace);
                throw new RVaadinException(lMessage);
            }

            File lJSONResultFile = new File(lFolder, RConstants.RJSONRESULTS);
            BufferedReader lReader = Files.newReader(lJSONResultFile, Charset.defaultCharset());

            loadJSON(lReader);

            // First try to clean the dashboard.
            iDashboard.removeAllTabs();

            handleImages();
            handleDataFrame();
            handleText();

        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        }

    }

    protected abstract void loadJSON(BufferedReader aReader);

    public abstract void handleImages();

    public abstract void handleDataFrame();

    public abstract void handleText();

    public void setDashBoardManager(DashBoardManager aDashBoardManager) {
        iDashboard = aDashBoardManager;
    }

    public Application getApplication() {
        return iApplication;
    }

    public void setApplication(Application aApplication) {
        iApplication = aApplication;
    }
}
